package com.savitar.common.aop;

import cn.hutool.core.date.DateTime;
import com.savitar.common.entity.BaseModel;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class OperationRecordAspect {

    @Pointcut("@annotation(com.savitar.common.annotation.Create)")
    private void createPointcut() {
    }

    @Pointcut("@annotation(com.savitar.common.annotation.Update)")
    private void updatePointcut() {
    }

    @Before("createPointcut()")
    public void createBefore(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            String className = arg.getClass().getSuperclass().getSimpleName();
            if (className.equals(BaseModel.class.getSimpleName())) {
                BaseModel baseModel = (BaseModel) arg;
                baseModel.setCreatedBy(SecurityContextHolder.getContext().getAuthentication().getName());
                baseModel.setCreatedTime(new DateTime());
            }
        }
    }

    @Before("updatePointcut()")
    public void updateBefore(JoinPoint joinPoint) {
        for (Object arg : joinPoint.getArgs()) {
            String className = arg.getClass().getSuperclass().getSimpleName();
            if (className.equals(BaseModel.class.getSimpleName())) {
                BaseModel baseModel = (BaseModel) arg;
                baseModel.setUpateBy(SecurityContextHolder.getContext().getAuthentication().getName());
                baseModel.setUpdateTime(new DateTime());
            }
        }
    }
}
